package com.leetroll.media.job;

import com.google.gson.JsonObject;
import com.leetroll.api.service.ItemService;
import com.leetroll.common.entity.Item;
import com.leetroll.common.enums.EFileType;
import com.leetroll.common.enums.EItemType;
import com.leetroll.common.utils.FileUtils;
import com.leetroll.common.utils.JsonUtils;
import com.leetroll.media.service.JobExecutor;
import com.leetroll.media.service.UpDownloadService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

@Service
@Slf4j
public class Job_Gumroad_VFX {

    private final ItemService itemService;
    private final UpDownloadService upDownloadService;
    private JobExecutor jobExecutor;

    public Job_Gumroad_VFX(ItemService itemService, UpDownloadService upDownloadService, JobExecutor jobExecutor) {
        this.itemService = itemService;
        this.upDownloadService = upDownloadService;
        this.jobExecutor = jobExecutor;
    }

    public static void prepForUpload() throws ExecutionException, InterruptedException {
        File folder = new File("F:\\_resources\\tutorial\\gumroad\\Compositing Academy - Gumroad - 200 FX Alpha VFX Asset Library");
        if (!folder.exists() || !folder.isDirectory()) return;

        File[] folders = folder.listFiles();
        if (folders == null) return;

        for (File sub : folders) {
            if (!sub.isDirectory() || sub.getName().equals("img") || sub.getName().equals("入库")) continue;
            cutAndZip(sub);
        }
        log.info("finished...");
    }

    private static Integer cutAndZip(File folder) {
        String parent = folder.getParent();
        String name = folder.getName().substring(folder.getName().indexOf(" ") + 1);
        String tgPath = parent + "\\入库\\" + name;
        createItemUploadDir(tgPath);
        List<File> mp4s = Arrays.stream(folder.listFiles()).filter(f -> f.getName().endsWith("mp4")).collect(Collectors.toList());
        if (mp4s.size() == 0) return 0;
        File mp4 = mp4s.get(0);
        try {
            FileUtils.copyFile(folder.getAbsolutePath() + "\\render.mp4", tgPath + "\\main\\" + mp4.getName());
            mp4.delete();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        FileUtils.toZip(folder.getAbsolutePath(), tgPath + "\\attach\\" + name + ".zip");
        return 1;
    }

    /**
     * 创建item上传相应文件夹
     * main  prev  attach
     *
     * @param tgPath 父文件夹
     */
    private static void createItemUploadDir(String tgPath) {
        String mainPath = tgPath + "\\main\\";
        String prevPath = tgPath + "\\prev\\";
        String attachPath = tgPath + "\\attach\\";
        FileUtils.creatDir(mainPath);
        FileUtils.creatDir(prevPath);
        FileUtils.creatDir(attachPath);
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        prepForUpload();
    }

    public void upload() throws InterruptedException, IOException, ExecutionException {
        File folder = new File("F:\\_resources\\tutorial\\gumroad\\Compositing Academy - Gumroad - 200 FX Alpha VFX Asset Library\\入库");
        if (!folder.exists() || !folder.isDirectory()) return;

        File[] folders = folder.listFiles();
        if (folders == null) return;

        for (File itemFolder : folders) {
//            if (!itemFolder.getName().equals("Abstract GlassyFire")) continue;
            jobExecutor.submit(() -> uploadItem(itemFolder));
        }
        jobExecutor.await();
    }

    private Integer uploadItem(File itemFolder) {
        log.info("----------------------准备插入 item[{}]----------------------", itemFolder.getName());
        File[] files = itemFolder.listFiles();
        if (files == null) return 0;

        //插入item表
        String name = itemFolder.getName();
        Item item = new Item();
        item.setName(name);
        item.setAlias(name);
        item.setCatId(1L);
        item.setStatus("show");
        item.setSource("Gumroad");
        item.setAuthor("Joshua");
        item.setPrice(5.0);
        item.setDesp("FX Alpha VFX");
        item.setType(EItemType.TEXTURE.getType());
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);

        for (File file : files) {
            if (file.isFile()) continue;

            if (file.getName().equals("main")) {
                //插入主图文件
                File mainFile = file.listFiles()[0];
                upDownloadService.upload2AliByType(item.getId(), mainFile, EFileType.MAIN);
                log.info("\t\t\t>> 主图插入成功");
            }  else if (file.getName().equals("attach")) {
                File attachFile = Objects.requireNonNull(file.listFiles())[0];
                upDownloadService.upload2AliByType(item.getId(), attachFile, EFileType.ATTACHMENT);
                log.info("\t>> 附件插入成功");
            }
        }

        return 1;
    }

}
